<template>
    <div class="allocate">
        <BasicDialogVue :data="dialog" @close="onCloseDialog(formRef)">
            <template #content>
                <div class="clue-container">
                    <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
                        <el-form-item label="角色名称：" prop="role">
                            <el-select clearable v-model="formData.role" @change="onChangeRole">
                                <el-option
                                    v-for="itemOption in roles"
                                    :key="itemOption.value"
                                    :label="itemOption.label"
                                    :value="itemOption.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="分配对象：" prop="userId">
                            <el-select clearable v-model="formData.userId">
                                <el-option
                                    v-for="itemOption in users"
                                    :key="itemOption.value"
                                    :label="itemOption.label"
                                    :value="itemOption.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="btn">
                    <el-button @click="onCloseDialog(formRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                </div>
            </template>
        </BasicDialogVue>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from 'element-plus'
import { ref, reactive, watchEffect, onMounted } from 'vue'
import BasicDialogVue from '@/components/baseDialog/Index.vue'
import { roleList } from '@/apis/company/role'
import { userList } from '@/apis/company/user'
import { clueAllocation } from '@/apis/clue'

const props = defineProps(['clueIds', 'visible'])
const emit = defineEmits(['close'])
let resubmit = false
const formRef = ref()
const dialog = reactive({
    visible: false,
    title: '编辑',
    width: '400px',
    id: '',
    type: 'create'
})
const formData = reactive({
    role: '',
    userId: ''
})
const rules = {
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
    userId: [{ required: true, message: '请选择分配对象', trigger: 'change' }]
}
const roles = reactive<{ value: string; label: string }[]>([])
const users = reactive<{ value: string; label: string }[]>([])

watchEffect(() => {
    dialog.visible = props.visible
})

onMounted(() => {
    getRoleList()
})

//拉取角色列表
const getRoleList = () => {
    roleList().then(res => {
        if (Number(res.data.code) === 200) {
            roles.length = 0
            res.data.result.forEach((item: any) => {
                roles.push({
                    value: item.id,
                    label: item.name
                })
            })
        }
    })
}

//监听选中的角色，获取该角色下的用户
const onChangeRole = (e: any) => {
    console.log(e)
    users.length = 0
    formData.userId = ''
    userList({ roleId: e, userType: 1 }).then(res => {
        if (Number(res.data.code) === 200) {
            users.length = 0
            res.data.result.forEach((item: any) => {
                users.push({
                    value: item.id,
                    label: item.name
                })
            })
        }
    })
}

//监听弹窗关闭
const onCloseDialog = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    formData.userId = ''
    emit('close')
}
//监听提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', formData)
            if (resubmit) {
                return
            }
            resubmit = true
            clueAllocation({ clueIds: props.clueIds, follower: formData.userId }).then(res => {
                resubmit = false
                if (Number(res.data.code) === 200) {
                    onCloseDialog(formEl)
                    ElMessage.success('分配成功')
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style scoped>
.btn {
    display: flex;
    justify-content: center;
    margin: 40px 0 16px 0;
}
</style>
